import 'package:flutter/material.dart';
import 'package:flutter_default_project/screen/home_screen.dart';
import 'package:flutter_default_project/typedefs.dart';
import 'package:todos_app_core/todos_app_core.dart';
import 'package:todos_repository_core/todos_repository_core.dart';
import 'package:todos_repository_local_storage/src/repository.dart';
import './models.dart';
import 'screen/add_edit_screen.dart';

class VanillaApp extends StatefulWidget {
  final TodosRepository todosRepository;
  const VanillaApp({super.key, required this.todosRepository});

  @override
  State<VanillaApp> createState() => _VanillaAppState();
}

class _VanillaAppState extends State<VanillaApp> {
  AppState appState = AppState.loading();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    widget.todosRepository.loadTodos().then((loadedTodos) {
      setState(() {
        appState = AppState(todos: loadedTodos.map(Todo.fromEntity).toList());
      });
    });
  }

  void updaterTodo(
    Todo todo, {
    bool? complete,
    String? id,
    String? task,
    String? note,
  }) {
    setState(() {
      todo.complete = complete ?? todo.complete;
      todo.task = task ?? todo.task;
      todo.note = note ?? todo.note;
      todo.id = id ?? todo.id;
    });
  }

  void addTodo(Todo todo) {
    setState(() {
      appState.todos.add(todo);
    });
  }

  void removeCompleteTodo() {
    setState(() {
      appState.todos.removeWhere((todo) => todo.complete);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: ArchSampleRoutes.home,
      routes: {
        ArchSampleRoutes.home: (context) => HomeScreen(
          appState: appState,
          todoUpdater: updaterTodo,
          removeComplete: removeCompleteTodo,
        ),
        ArchSampleRoutes.addTodo: (context) => AddEditScreen(onSave: addTodo),
      },
    );
  }
}
